package eventsys

import (
	"context"
	"fmt"
	"sync"
)

type EventType string

type Event[TData any] struct {
	Type EventType
	Data TData // 各种 Bo
}

// EventHandler 是处理事件的函数类型，使用泛型来指定事件数据的类型
type EventHandler[THandler any] func(ctx context.Context, event Event[THandler])

// Dispatcher 管理事件与处理器之间的映射
type Dispatcher struct {
	handlers map[EventType][]EventHandler[any]
	ch       chan Event[any]
	mu       sync.RWMutex
}

func NewDispatcher() *Dispatcher {
	return &Dispatcher{
		handlers: make(map[EventType][]EventHandler[any]),
		ch:       make(chan Event[any]),
	}
}

// Register 注册一个事件处理器
func (d *Dispatcher) Register(eventType EventType, handler EventHandler[any]) {
	d.mu.Lock()
	defer d.mu.Unlock()

	if eventType == "" || handler == nil {
		fmt.Println("Invalid event ")
		return
	}

	d.handlers[eventType] = append(d.handlers[eventType], handler)
}

// Dispatch 分发事件给所有注册过的处理器
func (d *Dispatcher) Dispatch(ctx context.Context) {

	for e := range d.ch {
		handlers, exists := d.handlers[e.Type]
		if !exists {
			fmt.Printf("No handlers registered for event type: %s\n", e.Type)
			return
		}
		// logs.CtxInfo("Dispatching event: %s\n", e.Type)
		for _, handler := range handlers {
			handler(ctx, e)
		}
	}
}

func (d *Dispatcher) ProduceEvent(ctx context.Context, event Event[any]) {
	d.ch <- event
}
